package start.doubudouyin.controller;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import start.doubudouyin.service.UsersinfoService;
import start.doubudouyin.utils.IconRead;
import start.doubudouyin.utils.IconRead.IconProcessResult;
import start.doubudouyin.utils.Result;

import java.io.IOException;

@RestController
@RequestMapping("/icon")
@CrossOrigin(origins = "http://localhost:5173")
public class IconController {

    private static final Logger log = LoggerFactory.getLogger(IconController.class);


    @Resource
    private UsersinfoService usersinfoService;
    //上传头像
    @PostMapping("/iconupload")
    public Result iconupload(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId) {
        try {
            // 1. 处理头像文件，获取存储信息
            IconRead.IconProcessResult fileResult = IconRead.processIconFile(file);
            String storedFileName = fileResult.storedFileName();

            // 2. 生成URL
            String iconUrl = IconRead.generateIconUrl(storedFileName);

            // 3. 保存头像信息到数据库
            usersinfoService.iconupload(iconUrl, userId);

            // 4. 返回包含URL的响应
            return Result.success("头像上传成功", iconUrl);
        } catch (IllegalArgumentException e) {
            return Result.error("400", e.getMessage());
        } catch (IOException e) {
            return Result.error("500", "文件处理失败: " + e.getMessage());
        } catch (Exception e) {
            return Result.error("500", "头像上传失败: " + e.getMessage());
        }
    }


    //编辑个人信息
    @PutMapping("/editpersonal")
    public Result editpersonal(@RequestParam("nickname") String nickname,
                               @RequestParam("signature") String signature,
                               @RequestParam("userId") String userId) {
        try {
            int affectedRows = usersinfoService.EditPersonal(nickname, signature, userId);
            if (affectedRows > 0) {
                return Result.success("个人信息编辑成功", null);
            } else {
                return Result.error("300", "信息编辑失败，未更新任何数据");
            }
        } catch (Exception e) {
            log.error("个人信息编辑异常", e);
            return Result.error("500", "信息编辑失败: " + e.getMessage());
        }
    }
}